The full text of this chapter, to read or revisit. To practise, do the exercises.
Exercise 1 — Damage Processor - Process Single Damage
Start building a damage processor!
- Create
process_damage(damage_value)
that converts damage_value to int
- If conversion fails: print "Invalid damage value!" and return 0
- Test with: 50, "30", "invalid", and None
Starter code
# Create process_damage function with ValueError and TypeError handling
# Test it
Exercise 2 — Damage Processor - Calculate Total Damage
Expand your damage processor to handle lists:
- Create
calculate_damage_list(damage_list)
that processes each damage and returns the total
- Test it with
damages
list.
Starter code
def process_damage(damage_value):
try:
return int(damage_value)
except Exception:
print("Invalid damage value!")
return 0
# Create calculate_damage_list function with loop
damages = [50, "30", 45, "invalid", None, "25"]
# Test it
Exercise 3 — Damage Processor - Average with Full Handling
Complete your damage processor with average calculation:
- Create
get_average_damage(damage_list)
that calculates the average damage
- Handle division by zero if no valid damages
- Print "Average calculated: [value]" in else block
- Print "Calculation complete!" in finally block
Starter code
def process_damage(damage_value):
try:
return int(damage_value)
except Exception:
print("Invalid damage value!")
return 0
def calculate_damage_list(damage_list):
total = 0
for damage in damage_list:
processed = process_damage(damage)
total = total + processed
return total
# Create get_average_damage function with try/except/else/finally
damages = [50, "30", 45, "invalid", None, "25"]
# Test it